import Toastify from "toastify-js";
import "toastify-js/src/toastify.css";

export function showNotification(message: string, theme = "dark") {
  Toastify({
    text: message,
    duration: 2000,
    close: true,
    gravity: "top",
    position: "right",
    stopOnFocus: true,
    style: {
      background: theme === "dark" ? "black" : "white",
      color: theme === "dark" ? "white" : "black"
    }
  }).showToast();
}

export interface CConnection {
  serverUrl: string;
  roomId: string;
}
export function createConnection({ serverUrl, roomId }: CConnection) {
  // 真正的实现会实际连接到服务器
  if (typeof serverUrl !== "string") {
    throw Error("Expected serverUrl to be a string. Received: " + serverUrl);
  }
  if (typeof roomId !== "string") {
    throw Error("Expected roomId to be a string. Received: " + roomId);
  }

  let intervalId: NodeJS.Timeout;
  let messageCallback: ((msg: string) => void) | undefined;

  return {
    connect() {
      console.log('✅ Connecting to "' + roomId + '" room at ' + serverUrl + "...");
      clearInterval(intervalId);
      intervalId = setInterval(() => {
        if (messageCallback !== undefined) {
          if (Math.random() > 0.5) {
            messageCallback("hey");
          } else {
            messageCallback("lol");
          }
        }
      }, 2000);
    },
    disconnect() {
      clearInterval(intervalId);
      messageCallback = undefined;
      console.log('❌ Disconnected from "' + roomId + '" room at ' + serverUrl + "");
    },
    on(event: string, callback: (msg: string) => void) {
      if (messageCallback !== undefined) {
        throw Error("Cannot add the handler twice.");
      }
      if (event !== "message") {
        throw Error('Only "message" event is supported.');
      }
      messageCallback = callback;
    }
  };
}
